// MMORPG游戏状态机类 - 以暗黑破坏神2为例
import { GAME_STATES } from './types';
import type { GameState, GameData } from './types';
import { StateManager } from './state-manager';
import { InputHandler } from './input-handler';
import { GameInitializer } from './game-initializer';
import { StateEventManager } from './state-event-manager';

export class RPGLogic {
  // 当前游戏状态
  private currentState: GameState;

  // 状态管理器实例
  private stateManager: StateManager;

  // 输入处理器实例
  private inputHandler: InputHandler;

  // 游戏初始化管理器实例
  private gameInitializer: GameInitializer;

  // 状态事件管理器实例
  private stateEventManager: StateEventManager;

  constructor() {
    // 初始化各个管理器
    this.stateManager = new StateManager();
    this.gameInitializer = new GameInitializer();
    this.stateEventManager = new StateEventManager();
    
    // 初始化输入处理器（传入状态管理相关方法）
    this.inputHandler = new InputHandler({
      forceStateChange: this.forceStateChange.bind(this)
    });

    // 初始化默认状态为探索状态
    this.currentState = GAME_STATES.EXPLORATION;

    // 进入初始状态
    this.stateManager.onEnterState(this.currentState);
  }

  // 更新当前状态
  public update(): void {
    // 保存当前状态用于比较
    const previousState = this.currentState;
    
    // 检查是否可以转换状态
    const possibleTransitions = this.stateManager.getTransitions(this.currentState);
    let newState: GameState | null = null;

    for (const transition of possibleTransitions) {
      if (transition.condition()) {
        newState = transition.to;
        break;
      }
    }

    // 如果状态可以转换，则执行状态转换
    if (newState && newState !== this.currentState) {
      this.stateManager.onExitState(this.currentState);
      this.currentState = newState;
      this.stateManager.onEnterState(this.currentState);
      
      // 触发状态变化事件
      this.stateEventManager.triggerStateChange(previousState, this.currentState);
    }

    // 更新当前状态
    this.stateManager.onUpdateState(this.currentState);
  }

  // 获取当前游戏状态
  public getCurrentState(): GameState {
    return this.currentState;
  }

  // 强制转换到指定状态
  public forceStateChange(state: GameState): boolean {
    if (!Object.values(GAME_STATES).includes(state)) {
      console.error(`无效的游戏状态：${state}`);
      return false;
    }

    if (state !== this.currentState) {
      const previousState = this.currentState;
      this.stateManager.onExitState(this.currentState);
      this.currentState = state;
      this.stateManager.onEnterState(this.currentState);
      
      // 触发状态变化事件
      this.stateEventManager.triggerStateChange(previousState, this.currentState);
      return true;
    }
    return false;
  }

  // 模拟触发特定状态转换的方法
  public triggerCombat(): void {
    if (this.currentState === GAME_STATES.EXPLORATION) {
      this.forceStateChange(GAME_STATES.COMBAT);
    }
  }

  public triggerDialogue(): void {
    if (this.currentState === GAME_STATES.EXPLORATION) {
      this.forceStateChange(GAME_STATES.DIALOGUE);
    }
  }

  public triggerDeath(): void {
    this.forceStateChange(GAME_STATES.DEATH);
  }

  public triggerResurrection(): void {
    if (this.currentState === GAME_STATES.DEATH) {
      this.forceStateChange(GAME_STATES.EXPLORATION);
    }
  }

  // ================ 初始化方法 ================
  
  /**
   * 游戏数据初始化方法
   * @param gameData 可选的游戏初始数据
   */
  public initializeGameData(gameData?: GameData): void {
    // 设置初始状态
    const initialState = this.gameInitializer.initializeGameData(gameData);
    if (initialState !== this.currentState) {
      this.stateManager.onExitState(this.currentState);
      this.currentState = initialState;
      this.stateManager.onEnterState(this.currentState);
    }
  }

  /**
   * 重置游戏状态
   */
  public reset(): void {
    this.stateManager.onExitState(this.currentState);
    this.currentState = GAME_STATES.EXPLORATION;
    this.stateManager.onEnterState(this.currentState);
    this.gameInitializer.resetGameData();
    console.log('游戏状态已重置');
  }

  // ================ 输入方法 ================

  /**
   * 处理键盘输入
   * @param key 按键名称
   * @param pressed 是否按下
   */
  public handleKeyInput(key: string, pressed: boolean): void {
    this.inputHandler.handleKeyInput(key, pressed, this.currentState);
  }

  /**
   * 处理鼠标输入
   * @param action 鼠标动作 (click, move, etc.)
   * @param position 鼠标位置
   * @param button 鼠标按钮 (left, right, middle)
   */
  public handleMouseInput(action: string, position: { x: number; y: number }, button?: string): void {
    this.inputHandler.handleMouseInput(action, position, button, this.currentState);
  }

  /**
   * 处理游戏事件
   * @param eventName 事件名称
   * @param eventData 事件数据
   */
  public handleGameEvent(eventName: string, eventData?: any): void {
    this.inputHandler.handleGameEvent(eventName, eventData);
  }

  // ================ 输出方法 ================

  /**
   * 获取游戏状态快照
   * @returns 包含当前游戏状态信息的对象
   */
  public getGameStateSnapshot() {
    const possibleTransitions = this.stateManager.getTransitions(this.currentState);
    const transitionStates = possibleTransitions.map(transition => transition.to);
    
    return this.gameInitializer.getGameStateSnapshot(this.currentState, transitionStates);
  }

  /**
   * 注册状态变化回调
   * @param callback 状态变化时执行的回调函数
   * @returns 取消注册的函数
   */
  public onStateChange(callback: (fromState: GameState, toState: GameState) => void): () => void {
    return this.stateEventManager.onStateChange(callback);
  }

  // ================ 扩展方法 ================

  /**
   * 获取玩家数据
   * @returns 当前玩家数据
   */
  public getPlayerData(): any {
    return this.gameInitializer.getPlayerData();
  }

  /**
   * 更新玩家数据
   * @param newData 新的玩家数据
   */
  public updatePlayerData(newData: any): void {
    this.gameInitializer.updatePlayerData(newData);
  }

  /**
   * 获取世界数据
   * @returns 当前世界数据
   */
  public getWorldData(): any {
    return this.gameInitializer.getWorldData();
  }

  /**
   * 更新世界数据
   * @param newData 新的世界数据
   */
  public updateWorldData(newData: any): void {
    this.gameInitializer.updateWorldData(newData);
  }
}